<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{form.projectNo}}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectRealName"
            label="项目名称*"
            prop="projectRealName" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectRealName"
              @blur="
                () => {
                  $refs.projectRealName.onFieldBlur()
                }
              "
              placeholder="真实名称，打印不显示"   
              :disabled="form.status>1 && !changeId" 
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A"   
              title="脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A"
            />
            <!--  :disabled="!changeId"  -->
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="mainDeptName"
            label="主导经营体"
            prop="mainDeptName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.mainDeptName"  
              @blur="
                () => {
                  $refs.mainDeptName.onFieldBlur()
                }
              "
              placeholder="请填写正确的组织架构名称，系统自动校验"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory" 
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <!-- <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions"  :disabled="form.id!=''"  
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select> -->
            <span style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ subName }}</span>

          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="implementPlace"
            label="横向品牌名称"
            prop="implementPlace"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.implementPlace"  
              @blur="
                () => {
                  $refs.implementPlace.onFieldBlur()
                }
              "
              placeholder="本项目的产品属于横向品牌的请填写横向品牌名称，没有的可以不填" title="本项目的产品属于横向品牌的请填写横向品牌名称，没有的可以不填"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            ref="hatchProjectNo"
            label="孵化项目编号"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.hatchProjectNo" placeholder="点击选择孵化项目" @click="hatch.visible = true"  :disabled="form.status>1" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="hatchProjectName"
            label="孵化项目名称"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.hatchProjectName" placeholder="点击选择孵化项目" @click="hatch.visible = true" :disabled="form.status>1" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="关联项目号"
            prop="lastProjectNo"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input v-model="form.lastProjectNo" @blur="checkPreProject" :disabled="tcDisabled" :placeholder="tcPlaceholder"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="关联项目名称" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            <a-input v-model="form.lastProjectName" placeholder="自动填充" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="keywords"
            label="关键词"
            prop="keywords"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-input
              v-model="form.keywords"
              @blur="
                () => {
                  $refs.keywords.onFieldBlur()
                }
              "
              placeholder="请输入与项目相关的关键词，多个关键词用中文分号[;]隔开，至少填写5个关键词，如：发酵、制曲、加热、降本、增鲜、增香"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item
            label="项目所属的品类"
            prop="highTechType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.highTechType"
              placeholder="请选择"
              :options="highCategoryOptions"
              @change="highCategoryChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="hasFermentation"
            label="是否属于发酵类"
            prop="hasFermentation"
            :label-col="{ span: 12 }"
            :wrapper-col="{ span: 15 }"
          >
           <a-radio-group v-model="form.hasFermentation">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="价值表属性"
            prop="valueTestType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select v-if="!form.id||form.status==1||!!changeId"
              v-model="form.valueTestType"
              placeholder="请选择"
              :options="valueTestTypeOptions"
                      @change="valueTestTypeChange"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
            <span v-else style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ form.valueTestTypeName }}</span>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="projectContent"
            label="项目内容概述"
            prop="projectContent"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.projectContent"
              @blur="
                () => {
                  $refs.projectContent.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-model-item label="是否需要工程动议" prop="isNeedEngineeringMotion">
            <a-radio-group v-model="form.isNeedEngineeringMotion">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
            <a-input v-model="form.motionProjectNameOrNo" placeholder="请输入动议项目名称或编号" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-if="resultsTradingCpu">
        <a-col :span="12">
          <a-form-model-item label="是否进行成果交易" prop="resultsTradingFlag">
            <a-radio-group v-model="form.resultsTradingFlag">
              <a-radio :value="true"> 是 </a-radio>
              <a-radio :value="false"> 否 </a-radio>
            </a-radio-group>
            <a-tooltip overlayClassName="tooltip_class">
              <template slot="title"  v-if="!form.id" >
                <span class="">请您先保存，再填写科技成果交易单</span>
              </template>
              <a-button type="primary" size="large" v-if="form.resultsTradingFlag" @click="goResultsTrading()">科技成果交易单</a-button>
            </a-tooltip>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            label="设计开发来源"
            prop="designSource"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-checkbox-group v-model="form.designSource" :options="designSourceOptions"> </a-checkbox-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="sourceBefore"
            class="self-form-item"
            label="来源于以前类似设计和开发活动的信息"
            prop="sourceBefore"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
           <a-radio-group v-model="form.sourceBefore">
              <a-radio value="是-有研发基础"> 是-有研发基础 </a-radio>
              <a-radio value="否-无研发基础"> 否-无研发基础 </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <div>
        <h3 style="margin-top:10px;"><b>技术目标</b></h3>
        <div style="display: flex; margin-top: 10px; margin-bottom: 10px" v-show="btnShow">
          <a-button type="primary" @click="techAdd()">新增</a-button>
          <a-button style="margin-left: 15px" class="default" @click="techDel()">删除</a-button>
        </div>
        <a-tooltip overlayClassName="tooltip_class" >
          <template slot="title">
            <span class="tooltipTitle">针对产品类项目，完整填写内容包括：</span><br>
1、质量：从色泽、香气、味道、体态、安全性等维度说明关键指标目标、应用效果目标；以及关键指取数依据。<br>
2、原料利用率目标以及取数依据；<br>
3、资源利用目标（如发酵周期等）以及取数依据。<br>
<span class="tooltipTitle">针对技术类项目，完整填写内容包括：</span><br>
1、从色泽、香气、味道、体态、安全性等维度说明技术应用前（改进前）和技术应用后（改进后）关键指标目标、应用效果目标；以及关键指标取数依据。<br>
2、成本（如收率）目标及关键指标取数依据；<br>
3、其他不产生影响的目标，明确可能带来的负面影响及说明。<br>
          </template>
        <a-table :row-selection="techUsedForRowSelection" :columns="techUsedFor.columns" :data-source="techUsedFor.data" bordered :key="techUsedFor.techFreshKey" :pagination="false">
          <template slot="dimension" slot-scope="text, record">
            <a-textarea v-model="record.dimension" :placeholder="record.placeholder" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
          <template slot="basisData" slot-scope="text, record">
            <a-textarea v-model="record.basisData" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
          <template slot="projectTarget" slot-scope="text, record">
            <a-textarea v-model="record.projectTarget" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
        </a-table>
        </a-tooltip>
      </div>
      <div>
        <h3 style="margin-top:10px;"><b>经济目标</b></h3>
        <div style="display: flex; margin-top: 10px; margin-bottom: 10px" v-show="btnShow">
          <a-button type="primary" @click="kpiAdd()">新增</a-button>
          <a-button style="margin-left: 15px" class="default" @click="kpiDel()">删除</a-button>
        </div>
        <a-tooltip overlayClassName="tooltip_class">
          <template slot="title">
            <span class="tooltipTitle">针对产品类项目，完整填写内容包括：</span><br>
1、产品首年销值（首批上市12个月内）目标及关键指标取数依据；<br>
2、产品毛利率目标及取数依据；<br>
3、内容物成本目标及取数依据。<br>
 <span class="tooltipTitle">针对技术类项目，完整填写内容包括：</span><br>
1、技术应用产生的经济效益目标及关键指标取数依据；<br>
2、其他不产生影响的目标，明确可能带来的负面影响及说明（如有，与技术目标不重复）。<br>
          </template>
        <a-table :row-selection="rowSelection" :columns="kpi.columns" :data-source="kpi.data" bordered :key="kpi.freshKey" :pagination="false" >
          <template slot="dimension" slot-scope="text, record">
            <a-textarea v-model="record.dimension" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" :placeholder="record.placeholder" />
          </template>
          <template slot="projectTarget" slot-scope="text, record">
            <a-textarea v-model="record.projectTarget"  :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
          <template slot="basisData" slot-scope="text, record">
            <a-textarea v-model="record.basisData" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
        </a-table>
        </a-tooltip>
      </div>
      <div>
        <h3 style="margin-top:10px;"><b>知产目标</b></h3>
        <a-table :row-selection="rowSelection" :columns="knowledgeKpi.columns" :data-source="knowledgeKpi.data" bordered :key="knowledgeKpi.freshKey" :pagination="false" >
          <template slot="knowledgeType" slot-scope="text, record">
            <a-textarea v-model="record.dimension" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
          <template slot="targetNum" slot-scope="text, record">
            <a-textarea v-model="record.projectTarget"  :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" v-if="record.dimension == '传承书'" placeholder="请填写目标产出数量，必须≥1" />
            <a-textarea v-model="record.projectTarget"  :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" v-if="record.dimension == '专利'" placeholder="请填写目标产出数量，如无或保密可填0" />
          </template>
          <template slot="remark" slot-scope="text, record">
            <a-textarea v-model="record.basisData" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" placeholder="请补充说明"/>
          </template>
        </a-table>
      </div>
      <div>
        <h3 style="margin-top:10px;"><b>其他目标</b></h3>
        <div style="display: flex; margin-top: 10px; margin-bottom: 10px" v-show="btnShow">
          <a-button type="primary" @click="otherKpiAdd()">新增</a-button>
          <a-button style="margin-left: 15px" class="default" @click="otherKpiDel()">删除</a-button>
        </div>
        <a-table :row-selection="otherRowSelection" :columns="otherKpi.columns" :data-source="otherKpi.data" bordered :key="otherKpi.freshKey" :pagination="false" >
          <template slot="dimension" slot-scope="text, record">
            <a-textarea v-model="record.dimension" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" :placeholder="record.placeholder" />
          </template>
          <template slot="projectTarget" slot-scope="text, record">
            <a-textarea v-model="record.projectTarget"  :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
          <template slot="basisData" slot-scope="text, record">
            <a-textarea v-model="record.basisData" :auto-size="{ minRows: 1, maxRows: 10 }" :maxLength="500" />
          </template>
        </a-table>
      </div>

      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'

export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '10',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectTypeSubCategory: '',
        projectType: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        lastProjectNo: '',
        lastProjectName: '',
        keywords: '',
        highTechType: '',
        isHighTechProject: false,
        isHighTechProjectText: '',
        projectContent: '',
        projectUseFor: '',
        isNeedEngineeringMotion: null,
        resultsTradingFlag:null,
        motionProjectNameOrNo: '',
        functionAndPerformance: '',
        sourceBefore: '',
        technologyTarget: '',
        economyTarget: '',
        implementPlace:'',
        name: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
        status: 0 ,
        hasFermentation:'',
        valueTestTypeName:''
      },
      rules: {
        projectName: [
          { required: true, message: '脱密名称,针对产品类项目，名称规则：年份（****年）+**（品类）产品+字母（按当年研发顺序用ABCDEF等大写字母代替）；如2021年酱油产品A', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        projectRealName: [
          { required: false, message: '真实名称，打印不显示', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        keywords: [
          {
            required: true,
            message: '请输入与项目相关的关键词，多个关键词用中文分号[;]隔开，至少填写5个关键词，如：菌种，发酵等',
            trigger: 'blur',
          },
          { min: 1, max: 127, message: '关键词不超过127个字符', trigger: 'blur' },
        ],
        projectContent: [
          { required: true, message: '请输入项目概述', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目概述不超过2000个字符', trigger: 'blur' },
        ],
        projectUseFor: [
          { required: true, message: '请输入项目应用场景', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目应用场景不超过2000个字符', trigger: 'blur' },
        ],
        technologyTarget: [
          { required: true, message: '请输入项目技术目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目技术目标不超过300个字符', trigger: 'blur' },
        ],
        economyTarget: [
          { required: true, message: '请输入项目经济目标', trigger: 'blur' },
          { min: 1, max: 300, message: '项目经济目标不超过300个字符', trigger: 'blur' },
        ],
        mainDeptName: [
          { required: true, message: '请输入主导经营体', trigger: 'blur' },
          { min: 1, max: 300, message: '主导经营体不超过300个字符', trigger: 'blur' },
        ],
        highTechType: [{ required: true, message: '请选择项目所属的品类', trigger: 'change' }],
        valueTestType: [{ required: true, message: '请选择价值表属性', trigger: 'change' }],
        designSource: [
          {
            type: 'array',
            required: true,
            message: '请选择设计开发来源',
            trigger: 'change',
          },
        ],
        isNeedEngineeringMotion: [{ required: true, message: '请选择是否需要工程动议', trigger: 'change' }],
        resultsTradingFlag: [{ required: true, message: '请选择是否进行成果交易', trigger: 'change' }],
        hasFermentation: [{ required: true, message: '请选择是否属于发酵类', trigger: 'change' }],
        desc: [{ required: true, message: '请选择是否需要工程动议', trigger: 'blur' }],
      },

      projectCategoryOptions: [],
      highCategoryOptions: [],
      designSourceOptions: [],
      valueTestTypeOptions: [],
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      hatch: {
        visible: false,
        title: '请选择孵化项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect',
        columns: [
          {
            title: '孵化项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '孵化项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      loadFinish: false,
      tcDisabled: false,
      tcPlaceholder: '',
      kpi: {
        columns: [
          {
            title: '维度',
            dataIndex: 'dimension',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'dimension' },
          },
          {
            title: '目标',
            dataIndex: 'projectTarget',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'projectTarget' },
          },
          {
            title: '取数依据',
            dataIndex: 'basisData',
            width: '34%',
            align: 'center',
            scopedSlots: { customRender: 'basisData' },
          },
        ],
        data: [],
        selRowIds: [],
        freshKey: 0,
      },
      knowledgeKpi: {
        columns: [
          {
            title: '知产成果类型',
            dataIndex: 'knowledgeType',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'knowledgeType' },
          },
          {
            title: '目标数量',
            dataIndex: 'targetNum',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'targetNum' },
          },
          {
            title: '备注说明',
            dataIndex: 'remark',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'remark' },
          }
        ],
        data: [],
        selRowIds: [],
        freshKey: 0,
      },
      otherKpi: {
        columns: [
          {
            title: '维度',
            dataIndex: 'dimension',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'dimension' },
          },
          {
            title: '目标',
            dataIndex: 'projectTarget',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'projectTarget' },
          },
          {
            title: '取数依据',
            dataIndex: 'basisData',
            width: '34%',
            align: 'center',
            scopedSlots: { customRender: 'basisData' },
          },
        ],
        data: [],
        selRowIds: [],
        freshKey: 0,
      },
      techUsedFor: {
        columns: [
          {
            title: '维度',
            dataIndex: 'dimension',
            width: '33%',
            align: 'center',
            scopedSlots: { customRender: 'dimension' },
          },
          {
            title: '目标',
            dataIndex: 'projectTarget',
            align: 'center',
            width: '33%',
            scopedSlots: { customRender: 'projectTarget' }
          },
          {
            title: '取数依据',
            dataIndex: 'basisData',
            align: 'center',
            scopedSlots: { customRender: 'basisData' },
            width: '34%',
          }
        ],
        data: [],
        selRowIds: [],
        techFreshKey: 0,
      },
      btnShow: false,
      canDoSave: this.$route.query.canDoSave ? (this.$route.query.canDoSave=='true' ? true : false) : true,
      techTypeList:['质量','原料利用率','资源利用','关键指标','应用效果'],		
      kpiProductTypeList:['产品首年销值','产品毛利率','内容物成本','成本'],
      knowledgeKpiTypeList: ['传承书','专利'],
      otherKpiTypeList:['能耗/环保目标','专利/技术传承书目标'],
      resultsTradings:[],
    }
  },
  computed: {
    rowSelection () {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.kpi.selRowIds = selectedRowKeys
        },
      }
    },
    techUsedForRowSelection () {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.techUsedFor.selRowIds = selectedRowKeys
        },
      }
    },
    otherRowSelection () {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.otherKpi.selRowIds = selectedRowKeys
        },
      }
    },
    resultsTradingCpu(){
      //计算科技成果交易单类型
     return this.resultsTradings.some(i=>{ return i.code == this.form.projectTypeSubCategory})
    }
  },
  methods: {
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      var validR=false;
      try{
        validR = await this.$refs.ruleForm.validate();
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      }catch(e){
        validR = false;
      }
      console.log('validR',validR);
      this.form.validResult = validR;
      let res=await this.doSave()
      this.projectBuildId=res;
      return {valid:validR,id:res};
    },
    async doSave() {
      let flag=null;
      var keywords = this.form.keywords
      if (strNotNull(keywords)) {
        let keywordLen = keywords.split('；').filter((x) => !!x).length
        if (keywordLen < 5 || keywordLen > 8) {
          this.$message.warning('请填写5-8个关键词, 中文分号[；]分隔');
          return flag;
        }
      }
      if(this.knowledgeKpi.data.length > 0) {
        var bookNum = this.knowledgeKpi.data[0].projectTarget
        var bookNumPatt = /^[1-9]\d*$/
        if(!bookNumPatt.test(bookNum)) {
          this.$message.warning('请填写目标产出数量，必须≥1');
          return flag
        }
        var patentNum = this.knowledgeKpi.data[0].projectTarget
        var patentNumPatt = /^[1-9]\d*|0$/
        if(!patentNumPatt.test(patentNum)) {
          this.$message.warning('请正确填写目标产出数量，如无或保密可填0');
          return flag
        }
      }
      let arr = []
      this.form.techList = arr.concat(this.kpi.data,this.techUsedFor.data,this.knowledgeKpi.data,this.otherKpi.data)
      //设置附加类型，科技项目使用价值表属性作为附加字段
      this.form.additionType=this.form.valueTestType;
      var formData = JSON.parse(JSON.stringify(this.form));

      if (formData.designSource!=null && formData.designSource.length>0) {
        formData.designSource = formData.designSource.join(',')
      }else{
        formData.designSource = '';
      }
      formData.changeId=this.changeId;
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id;
            vm.form.projectNo = res.result.projectNo;
            this.$message.success('保存成功')
            return flag=res.result.id;
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
        return flag;
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    //初始化项目所属的品类
    initHighCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目所属高企大类' })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.highCategoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目所属高企大类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目所属高企大类失败:' + res.message)
        })
    },
    //立项设计来源选项
    initSourceDesign() {
      var vm = this
      getAction(vm.url.codeInfoList, { type: '项目立项设计来源' }).then((res) => {
        if (res.code == 200) {
          res.result.records.forEach((element) => {
            vm.designSourceOptions.push({
              label: element.name,
              value: element.code,
            })
          })
        } else {
          this.$message.warning('加载【项目立项设计来源】选项有误：' + res.message)
        }
      })
    },
    initValueTestType() {
      var vm = this
      getAction(vm.url.codeInfoList, { type: '科技项目价值表属性' }).then((res) => {
        if (res.code == 200) {
          res.result.records.forEach((element) => {
            vm.valueTestTypeOptions.push({
              label: element.name,
              value: element.code,
            })
          })
          if(!!vm.form.id&&!!vm.form.valueTestType){
            let valueType=vm.valueTestTypeOptions.filter(v=>v.value==vm.form.valueTestType);
            if(valueType&&valueType.length>0){
              vm.$set(vm.form, 'valueTestTypeName', valueType[0].label)
            }
          }
        } else {
          this.$message.warning('加载【项目立项设计来源】选项有误：' + res.message)
        }
      })
    },
    //孵化项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
      }
      this.hatch.visible = false
    },
    //校验关联项目号
    checkPreProject() {
      if (this.form.lastProjectNo != null && this.form.lastProjectNo.length > 0) {
        var vm = this
        getAction(this.url.getProjectByNo, { projectNo: this.form.lastProjectNo })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form.lastProjectName = result.projectName
              } else {
                this.form.lastProjectNo = ''
                vm.$message.warning('请输入有效的【关联项目号】')
              }
            } else {
              this.$message.warning('查询关联项目失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('查询关联项目失败:' + res.message)
          })
      }
    },
    initSubName () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0,parentid:vm.form.projectClass,code:vm.form.projectTypeSubCategory})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
    //高企大类变化，设置高企标识
    highCategoryChange() {
      var highCategory = this.form.highTechType
      this.form.isHighTechProjectText =
        highCategory == null || highCategory == '' ? '' : highCategory === '99' ? '非高企项目' : '高企项目'
      if (this.form.isHighTechProjectText == '高企项目') {
        this.form.isHighTechProject = true
      }else{
        this.form.isHighTechProject = false
      }
    },
    valueTestTypeChange(){
      if(this.form.additionType!=this.form.valueTestType){
        this.$info({
          title: '提示',
          content: "价值表属性更改，如果您已经保存了价值表或者核心力值表，则需要重跑试题" ,
          onOk() {},
        });
      }
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId:this.changeId})
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                // if (this.form.isHighTechProject) {
                //   this.form.isHighTechProjectText = '高企项目'
                // } else {
                //   this.form.isHighTechProjectText = '非高企项目'
                // }
                //设计开发来源
                var ds = vm.form.designSource
                if (ds == undefined || ds == null || ds == '') {
                  vm.form.designSource = []
                } else {
                  vm.form.designSource = ds.split(',')
                }
                if(!!vm.form.id&&!!vm.form.valueTestType){
                  let valueType=vm.valueTestTypeOptions.filter(v=>v.value==vm.form.valueTestType);
                  if(valueType&&valueType.length>0){
                    vm.$set(vm.form, 'valueTestTypeName', valueType[0].label)
                  }
                }

                if (result.techList != null) {
                  this.techUsedFor.data = result.techList.filter(item => item.baseType && item.baseType == 1 && item.channel && item.channel == '1')
                  this.techUsedFor.data.forEach((item) => {
                    item.key = item.id
                  })

                  this.kpi.data = result.techList.filter(item => item.baseType && item.baseType == 2 && item.channel && item.channel == '1')
                  this.kpi.data.forEach((item) => {
                    item.key = item.id
                  })

                  this.knowledgeKpi.data = result.techList.filter(item => item.baseType && item.baseType == 3 && item.channel && item.channel == '1')
                  this.knowledgeKpi.data.forEach((item) => {
                    item.key = item.id
                  })

                  this.otherKpi.data = result.techList.filter(item => item.baseType && item.baseType == 9 && item.channel && item.channel == '1')
                  this.otherKpi.data.forEach((item) => {
                    item.key = item.id
                  })  
                }

                this.initSubName()
                this.loadFinish=true
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish=true
      }
    },
    kpiAdd () {
      this.kpi.data.push({
        key: this.kpi.data.length + 1 + new Date().getTime(),
        strId: '',
        dimension: '',
        projectTarget: '',
        basisData: '',
        baseType: 2,
        channel:1
      })
    },
    kpiDel () {
      if (this.kpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的经济目标记录')
        return
      }
      var vm = this;
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          console.log('OK')
          // 在这里调用删除接口
          for (var i = 0; i < vm.kpi.selRowIds.length; i++) {
            for (var j = vm.kpi.data.length - 1; j >= 0; j--) {
              if (vm.kpi.data[j].key == vm.kpi.selRowIds[i]) {
                vm.kpi.data.splice(j, 1)
                break
              }
            }
          }
          vm.kpi.selRowIds = []
          vm.kpi.freshKey++
        },
        onCancel () {
          console.log('Cancel')
        },
      })
    },
    otherKpiAdd () {
      this.otherKpi.data.push({
        key: this.otherKpi.data.length + 1 + new Date().getTime(),
        strId: '',
        dimension: '',
        projectTarget: '',
        basisData: '',
        baseType: 9,
        channel:1
      })
    },
    otherKpiDel () {
      if (this.otherKpi.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的其他目标记录')
        return
      }
      var vm = this;
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          // 在这里调用删除接口
          for (var i = 0; i < vm.otherKpi.selRowIds.length; i++) {
            for (var j = vm.otherKpi.data.length - 1; j >= 0; j--) {
              if (vm.otherKpi.data[j].key == vm.otherKpi.selRowIds[i]) {
                vm.otherKpi.data.splice(j, 1)
                break
              }
            }
          }
          vm.otherKpi.selRowIds = []
          vm.otherKpi.freshKey++
        },
        onCancel () {
          console.log('Cancel')
        },
      })
    },
    techAdd () {
      this.techUsedFor.data.push({
        key: this.techUsedFor.data.length + 1 + new Date().getTime(),
        strId: '',
        dimension: '',
        basisData: '',
        projectTarget: '',
        baseType: 1,
        channel:1
      })
    },
    techDel () {
      if (this.techUsedFor.selRowIds.length == 0) {
        this.$message.warning('请选择要删除的技术目标记录')
        return
      }
      var vm = this;
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          // 在这里调用删除接口
          for (var i = 0; i < vm.techUsedFor.selRowIds.length; i++) {
            for (var j = vm.techUsedFor.data.length - 1; j >= 0; j--) {
              if (vm.techUsedFor.data[j].key == vm.techUsedFor.selRowIds[i]) {
                vm.techUsedFor.data.splice(j, 1)
                break
              }
            }
          }
          vm.techUsedFor.selRowIds = []
          vm.techUsedFor.techFreshKey++
        },
        onCancel () {
          console.log('Cancel')
        },
      })
    },
    initListData(){
      const _this = this
      this.techTypeList.forEach(item => {
        _this.techUsedFor.data.push({
          key: _this.techUsedFor.data.length + 1 + new Date().getTime(),
          strId: '',
          dimension: '',
          basisData: '',
          projectTarget: '',
          baseType: 1,
          channel:1,
          placeholder:'如：'+item
        })
      })
      this.kpiProductTypeList.forEach(item => {
        this.kpi.data.push({
          key: this.kpi.data.length + 1 + new Date().getTime(),
          strId: '',
          dimension: '',
          projectTarget: '',
          basisData: '',
          baseType: 2,
          channel:1,
          placeholder:'如：'+item
        })
      })
      this.knowledgeKpiTypeList.forEach(item => {
        _this.knowledgeKpi.data.push({
          key: _this.knowledgeKpi.data.length + 1 + new Date().getTime(),
          strId: '',
          dimension: item,
          projectTarget: '',
          basisData: '',
          baseType: 3,
          channel:1,
          placeholder:''
        })
      })
      this.otherKpiTypeList.forEach(item => {
        _this.otherKpi.data.push({
          key: _this.otherKpi.data.length + 1 + new Date().getTime(),
          strId: '',
          dimension: item,
          projectTarget: '',
          basisData: '',
          baseType: 9,
          channel:1,
          placeholder:''
        })
      })
      
    },
    //成果项目类型
    initResultsTrading() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '成果项目类型', isdel: 0 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null ) {
              vm.resultsTradings = list.records
            }
          } else {
            this.$message.warning('查询成果项目类型失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询成果项目类型失败:' + res.message)
        })
    },
    goResultsTrading(){
      if(!this.form.id){
        
        this.$message.warning('请您先保存，再填写科技成果交易单')
        return
      }
      let urlJump = this.$router.resolve({ path: '/techResult/addOrder?projectBuildId=' + this.form.id+'&createType=1' })
      window.open(urlJump.href, '_blank')
    }
  },
  mounted() {
    if (this.projectBuildId == null || this.projectBuildId == '') {
        this.form.projectType = this.selProjectType
        this.form.projectTypeSubCategory = this.selProjectType
        this.form.mainDeptName = Vue.ls.get(USER_INFO).deptName
        if ( this.selProjectType == 'TC') {
          this.tcDisabled = true
          this.tcPlaceholder = '自动关联PA类型项目带出'
        } else {
          this.tcDisabled = false
          this.tcPlaceholder = ''
        }
        this.initSubName()
        this.initListData()
    }
    this.btnShow=this.canDoSave;
    this.initProjectCategoryOptions()
    this.initHighCategoryOptions()
    this.initSourceDesign()
    this.initValueTestType()
    this.initResultsTrading()
    this.initData()
  },
}
</script>
<style lang="less" >
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
}
.tooltip_class{
  max-width: 600px !important;
  .tooltipTitle{
    font-weight: bold;
    color: red;
    font-size: 15px;
  }
}
.self-form-item{
  .ant-form-item-label{width: 266px;}
}
</style>